package com.innovation.chengzhangriji.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputLayout;
import android.support.v7.widget.ListPopupWindow;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.BabyQRCodeResponse;
import com.innovation.chengzhangriji.http.BabyResponse;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.widget.CuteButton;
import com.innovation.chengzhangriji.ui.widget.CuteEditText;
import com.orhanobut.logger.Logger;

/**
 * 扫码加入宝宝日记
 */
public class Select2Fragment extends BaseFragment implements AdapterView.OnItemClickListener, View.OnTouchListener, View.OnClickListener {

    private static final String[] list = new String[]{"爸爸", "妈妈", "爷爷", "奶奶", "姥爷", "姥姥"};
    private CuteEditText mInputName;
    private ListPopupWindow lpw;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Config.REQUEST_OPEN_SCAN && resultCode == Activity.RESULT_OK) {
            getBabyIDByQRCode(data.getStringExtra(Config.ACTION_EXTERNAL_RESULT_QRCDOE));
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_create2, container, false);
        CuteButton button = (CuteButton) view.findViewById(R.id.button_scan);
        TextInputLayout inputLayoutName = (TextInputLayout) view.findViewById(R.id.text_input_layout_name);
        inputLayoutName.setHint("您是宝贝的?");
        mInputName = (CuteEditText) view.findViewById(R.id.text_input_name);
        lpw = new ListPopupWindow(getActivity());
        lpw.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, list));
        lpw.setAnchorView(mInputName);
        lpw.setModal(true);
        lpw.setOnItemClickListener(this);
        mInputName.setOnTouchListener(this);
        button.setOnClickListener(this);
        return view;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String item = list[position];
        mInputName.setText(item);
        lpw.dismiss();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        final int DRAWABLE_RIGHT = 2;
        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (event.getRawX() >= (mInputName.getRight() - mInputName.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
                lpw.show();
                return true;
            }
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.button_scan) {
            startCaptureActivityForResult();
        }
    }

    private void startTimelineActivity() {
        Intent intent = new Intent(getActivity(), HomeActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        getActivity().finish();
    }

    private void startCaptureActivityForResult() {
        Intent intent = new Intent(getActivity(), CaptureActivity.class);
        startActivityForResult(intent, Config.REQUEST_OPEN_SCAN);
    }

    // 根据二维码获得宝贝信息
    private void getBabyIDByQRCode(String qrcode) {
        LoginInfo login = Config.getLoginInfo(getActivity());
        if (login == null) {
            return;
        }
        String phone = login.getPhone();
        String token = login.getToken().getAccessToken();
        String member = mInputName.getText().toString();
        Client.requestBabyQRCode(getActivity(), phone, token, member, qrcode, new ResponseHandler() {

            @Override
            public void onInnovationStart() {
                showProgressDialog(null, null);
            }

            @Override
            public void onInnovationSuccess(JsonElement value) {
                Logger.d("扫码结果" + value.toString());
                BabyQRCodeResponse response = get(value.toString(), BabyQRCodeResponse.class);
                if (response != null) {
                    requestJoin(response.getId());
                }
                dismissProgressDialog();
            }

            @Override
            public void onChZhRJFailure(String value) {
                dismissProgressDialog();
                tipShow(value);
            }
        }, networkUnavailableSampleImpl());
    }

    private void requestJoin(int babyID) {
        LoginInfo loginInfo = Config.getLoginInfo(getActivity());
        if (loginInfo == null) {
            return;
        }
        String phone = loginInfo.getPhone();
        String token = loginInfo.getToken().getAccessToken();
        String role = mInputName.getText().toString();
        Client.requestJoin(getActivity(), phone, token, babyID, role, new ResponseHandler() {

            @Override
            public void onStart() {
                showProgressDialog(null, null);
            }

            @Override
            public void onInnovationSuccess(JsonElement value) {
                if (value.getAsInt() == 1) {
                    tipShow("申请成功！坐待对方验证吧！");
                    startTimelineActivity();
                } else {
                    tipShow("未知的错误");
                }
            }

            @Override
            public void onChZhRJFailure(String value) {
                tipShow(value);
            }

            @Override
            public void onInnovationFinish() {
                dismissProgressDialog();
            }

            @Override
            public void onInnovationExceptionFinish() {
                dismissProgressDialog();
            }
        }, networkUnavailableSampleImpl());
    }
}
